package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_apply.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-08-06
 * description:
 */
class ShopApplyFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: ShopApplyViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_apply, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    button_apply.setOnClickListener(this)

    observeData()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_apply -> {

        val name = edit_text_name.text.toString()
        if (name.isBlank()) {
          toast("请输入名称")
          return
        }

        viewModel.storeApply(name)
      }
    }
  }

  private fun observeData() {
    viewModel.storeApply.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("storeApply = %s", it)
      when (it) {
        is Data.Loading -> {
          button_apply.isEnabled = false
        }
        is Data.Error -> {
          button_apply.isEnabled = true
        }
        is Data.Success -> {
          button_apply.isEnabled = true
          toast("申请成功")

          // 转到功能页面
          findNavController().navigate(R.id.action_shopApplyFragment_to_shopManageFragment)
        }
      }
    })
  }
}